// Fill out your copyright notice in the Description page of Project Settings.


#include "SnakeBase.h"
#include "SnakeElementBase.h"

// Sets default values
ASnakeBase::ASnakeBase()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;
	ElementSize = 100.0f;
	SnakeSpeed = 10.0f;
	LastMoveDirection = EMovementDirection::UP;
}

// Called when the game starts or when spawned
void ASnakeBase::BeginPlay()
{
	Super::BeginPlay();
	SetActorTickInterval(SnakeSpeed);
	AddSnakeElement(4);
	SnakeElements[0]->SetFirstElementType();
}

// Called every frame
void ASnakeBase::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
	Move();
}

void ASnakeBase::AddSnakeElement(int ElementsCount)
{
	for (int i = 0; i < ElementsCount; i++)
	{
		FTransform NewElementTransform = FTransform(GetActorLocation() - FVector(SnakeElements.Num() * ElementSize, 0.0f, 0.0f));
		ASnakeElementBase* NewElement = GetWorld()->SpawnActor<ASnakeElementBase>(SnakeElementClass, NewElementTransform);
		SnakeElements.Add(NewElement);
	}
}

void ASnakeBase::Move()
{
	FVector MovementVector = FVector().ZeroVector;
	float DeltaSpeed = ElementSize;
	switch (LastMoveDirection)
	{
	case EMovementDirection::UP:
		MovementVector.X += DeltaSpeed;
		break;
	case EMovementDirection::DOWN:
		MovementVector.X -= DeltaSpeed;
		break;
	case EMovementDirection::LEFT:
		MovementVector.Y += DeltaSpeed;
		break;
	case EMovementDirection::RIGHT:
		MovementVector.Y -= DeltaSpeed;
		break;
	default:
		break;
	}
	for (int i = SnakeElements.Num() - 1; i > 0; i--)
	{
		ASnakeElementBase* CurrentElement = SnakeElements[i];
		ASnakeElementBase* PreviousElement = SnakeElements[i - 1];
		FVector PreviousLocation = PreviousElement->GetActorLocation();
		CurrentElement->SetActorLocation(PreviousLocation);
	}
	SnakeElements[0]->AddActorWorldOffset(MovementVector);
}

